/**
 * Created by admin on 2017/10/26.
 */
$(document).ready(function() {
    var compare = function (obj1, obj2) {
        var val1 = obj1.ope_id;
        var val2 = obj2.ope_id;
        if (val1 < val2) {
            return -1;
        } else if (val1 > val2) {
            return 1;
        } else {
            return 0;
        }
    };
    
    var VAL = {
    	NORMAL      : "0000000"  ,
    	EVT_USER    : $("#userId").text(),
    	T_FDPAPLYWO : "FDPAPLYWO",
    	T_FBPBISOPE : "FBPBISOPE",
    	T_FBPBISTOL : "FBPBISTOL",
    	T_FIPINQSHT : "FIPINQSHT",
    	T_FPPMOVEIN : "FPPMOVEIN",
        T_FPPMOVEOUT: "FPPMOVEOUT",
        T_FBPBISPTH : "FBPBISPTH",
        T_MSPLINEWO : "MSPLINEWO",
    };
    
    var domObj = {
        buttons : {
            $move_in_btn : $("#move_in_btn")
        },
        
        $bayIdSel    : $("#bayIdSel"),
        $opeIdSel    : $("#opeIdSel"),
        $toolIdSel   : $("#toolIdSel"),
        $woCateSel   : $("#woCateSel"),
        $woIdSel     : $("#woIdSel"),
        $prdSeqIdTxt : $("#prdSeqIdTxt"),
        
        grids : {
            $prodListDiv : $("#prodListDiv"),
            $prodListGrd : $("#prodListGrd"),
            $prodListPg : $("#prodListPg"),
        },        
    };
    
    /**
     * grid  initialization
     */
    var iniGridInfo = function() {
        domObj.grids.$prodListGrd.jqGrid({
	        url: "",
	        datatype: "local",
	        mtype: "POST",
	        autowidth: false,
	        shrinkToFit: false,
	        resizable: true,
	        loadonce: true,
	        viewrecords: true,
	        rownumbers: true,
	        rowNum: 20,
	        emptyrecords: true,
	        colModel: [
	            {
	                name: 'prd_seq_id',
	                index: 'prd_seq_id',
	                label: SHEET_ID_TAG,
	                width: 150
	            },  {
	                name: 'prd_stat',
	                index: 'prd_stat',
	                label: PRD_STAT_TAG,
	                width: 100
	            },{
	                name: 'prd_grade',
	                index: 'prd_grade',
	                label: PRD_GRADE_TAG,
	                width: 100
	            }, {
	                name: 'lot_id_fk',
	                index: 'lot_id_fk',
	                label: LOT_ID_TAG,
	                width: 150
	            }, {
	                name: 'wo_id_fk',
	                index: 'wo_id_fk',
	                label: WO_ID_TAG,
	                width: 150
	            },{
	                name: 'mdl_id_fk',
	                index: 'mdl_id_fk',
	                label: MDL_ID_TAG,
	                width: 200
	            }, {
	                name: 'path_id_fk',
	                index: 'path_id_fk',
	                label: PATH_ID_TAG,
	                width: 100
	            }, {
	                name: 'path_ver_fk',
	                index: 'path_ver_fk',
	                label: PATH_VER_TAG,
	                width: 100
	            }, {
	                name: 'ope_id_fk',
	                index: 'ope_id_fk',
	                label: OPE_ID_TAG,
	                width: 100
	            }, {
	                name: 'ope_no_fk',
	                index: 'ope_no_fk',
	                label: OPE_NO_TAG,
	                width: 100
	            }, {
	                name: 'ope_ver_fk',
	                index: 'ope_ver_fk',
	                label: OPE_VER_TAG,
	                width: 100
	            }, {
	                name: 'proc_id_fk',
	                index: 'proc_id_fk',
	                label: PROC_ID_TAG,
	                width: 100
	            },{
	                name: 'tool_id_fk',
	                index: 'tool_id_fk',
	                label: TOOL_ID_TAG,
	                width: 100
	            }],
	        pager: "#prodListPg"
	    });
	};
    
    /**
     * All tool functions
     * @type {Object}
     */
    var toolFunc = {
    	resizeFnc : function(){
            var offsetBottom, grdDivWidth;
            grdDivWidth = $("#divTop").width();
            offsetBottom = $(window).height() - domObj.grids.$prodListDiv.offset().top;

            domObj.grids.$prodListDiv.width(grdDivWidth);
            domObj.grids.$prodListDiv.height(offsetBottom);
            domObj.grids.$prodListGrd.setGridWidth(grdDivWidth);
            domObj.grids.$prodListGrd.setGridHeight(offsetBottom*0.95-51);
    	},
        initBayArea : function(){
            comAddValueByDataCateFnc("#bayIdSel", "AREA", "data_ext", "data_desc", true);
        },
        initWoCate: function(){
            comAddValueByDataCateFnc("#woCateSel", "WOCT", "data_ext", "data_desc", true);
        },
        iniWoIdSel : function(){
            var wo_cate = $.trim(domObj.$woCateSel.val());
            var inObj = {
                trx_id : VAL.T_FDPAPLYWO,
                action_flg : "Q",
                iary : [{
                    wo_cate  : wo_cate
                }]
            };
            var outObj = comTrxSubSendPostJson(inObj);
            if (outObj.rtn_code == VAL.NORMAL) {
                var oaryA = outObj.oary;
                oaryA.sort(compare);
                SelectDom.addSelectArr(domObj.$woIdSel, oaryA, "wo_id","wo_id","",true);
            }
        },
        iniOpeIdSel : function(){
            var inObj = {
                trx_id : VAL.T_FBPBISOPE,
                action_flg : "L"
            };
            var outObj = comTrxSubSendPostJson(inObj);
            if (outObj.rtn_code == VAL.NORMAL) {
                var oaryA = outObj.oary;
                oaryA.sort(compare);
                toolFunc.addSelectOpe(domObj.$opeIdSel, oaryA, "ope_id","ope_id","ope_dsc",true);
            }
        },
        iniToolIdSel : function(){
            var bay_id  = $.trim(domObj.$bayIdSel.val());
            var ope_id = $.trim(domObj.$opeIdSel.val());
            if(bay_id==""||ope_id==""){
                return;
            }
            var inObj = {
                trx_id : VAL.T_FBPBISTOL,
                action_flg : "M",
                iary : [{
                    bay_id      : bay_id,
                    ope_id_fk   : ope_id
                }]
            };
            var outObj = comTrxSubSendPostJson(inObj);
            if (outObj.rtn_code == VAL.NORMAL) {
                SelectDom.addSelectArr_(domObj.$toolIdSel, outObj.oary, "tool_id","tool_id","tool_dsc",true);
            }
        },
        queryPrdInfo : function(){
        	var prd_seq_id = $.trim(domObj.$prdSeqIdTxt.val());
        	if(!prd_seq_id){
                showErrorDialog("", "请输入屏体代码");
                return false;
        	}
            var wo_id = $.trim(domObj.$woIdSel.val());
            var ope_id = $.trim(domObj.$opeIdSel.val());
            var inObj = {
                trx_id     : VAL.T_FIPINQSHT,
                action_flg : "Q",
                prd_seq_id : prd_seq_id
            };
            var outObj = comTrxSubSendPostJson(inObj);
            if (outObj.rtn_code == VAL.NORMAL) {
                //检查工艺路线
                 var nxPathIdFk = outObj.nx_path_id_fk;
                 var nxPathVerFk = outObj.nx_path_ver_fk;
                 var iary1 = {
                     path_id : nxPathIdFk,
                     path_ver : nxPathVerFk
                 }
                 var inObj1 = {
                     trx_id     : VAL.T_FBPBISPTH,
                     action_flg : "Q",
                     iaryA : [iary1]
                 }
                var outObj1 = comTrxSubSendPostJson(inObj1);
                if (outObj1.rtn_code == VAL.NORMAL) {
                    if(outObj1.oaryA != null && outObj1.oaryA[0].path_cate == 'RWK'){
                        showErrorDialog("","该玻璃下一个工艺路线为重工工艺，需在重工过账界面过账！");
                        return false;
                    }
                }
            	setGridInfo(outObj, "#prodListGrd");
            	if(outObj.prd_stat !== "WAIT"){
            	    //检查屏体是需要自动出账
                    var prd_stat = outObj.prd_stat;
                    var inObj = {
                        trx_id     : VAL.T_FIPINQSHT,
                        evt_usr    : VAL.EVT_USER,
                        action_flg  : 'R',
                        wo_id   :  wo_id,
                        ope_id  : ope_id,
                        prd_seq_id : prd_seq_id
                    };
                    var outObj = comTrxSubSendPostJson(inObj);
                    if (outObj.rtn_code == VAL.NORMAL) {
                        if(outObj.skip_flg=="2"){
                            var iaryOut = {
                                prd_seq_id: prd_seq_id,
                                prd_judge:"OK"
                            }
                            var inObjOut = {
                                trx_id: VAL.T_FPPMOVEOUT,
                                evt_usr: VAL.EVT_USER,
                                action_flg: 'O',
                                iary: [iaryOut]
                            };
                            var outObjOut = comTrxSubSendPostJson(inObjOut);
                            if (outObjOut.rtn_code == VAL.NORMAL) {
                                //自动出账成功后
                                var inObj = {
                                    trx_id     : VAL.T_FIPINQSHT,
                                    evt_usr    : VAL.EVT_USER,
                                    action_flg  : 'Q',
                                    prd_seq_id : prd_seq_id
                                };
                                var outObj = comTrxSubSendPostJson(inObj);
                                if (outObj.rtn_code == VAL.NORMAL) {
                                    if(outObj.nx_toolg_id_fk == "$FMA"||outObj.nx_toolg_id_fk == "$FQC"||outObj.nx_toolg_id_fk == "$MPK"){
                                        showErrorDialog("", "屏体站点为[" + outObj.ope_id_fk + "]，请去该站点入账");
                                        return false;
                                    }else if(outObj.ope_id_fk !== ope_id){
                                        showErrorDialog("", "屏体站点代码不匹配，屏体站点为[" + outObj.ope_id_fk + "]");
                                        return false;
                                    }else if(outObj.wo_id_fk !== wo_id){
                                        showErrorDialog("", "屏体工单代码不匹配，屏体工单为[" + outObj.wo_id_fk + "]");
                                        return false;
                                    }
                                    //入账
                                    btnFunc.move_in_func();
                                }
                            }
                        }else{
                            //不需要自动出账，则报错
                            showErrorDialog("", "屏体状态不正确，必须为[WAIT],当前状态为[" + prd_stat + "]");
                            return false;
                        }
                    }
            	}else {
                    if(outObj.nx_toolg_id_fk == "$FMA"||outObj.nx_toolg_id_fk == "$FQC"||outObj.nx_toolg_id_fk == "$MPK"){
                        showErrorDialog("", "屏体站点为[" + outObj.ope_id_fk + "]，请去该站点入账");
                        return false;
                    }else if(outObj.ope_id_fk !== ope_id){
                        showErrorDialog("", "屏体站点代码不匹配，屏体站点为[" + outObj.ope_id_fk + "]");
                        return false;
                    }else if(outObj.wo_id_fk !== wo_id){
                        showErrorDialog("", "屏体工单代码不匹配，屏体工单为[" + outObj.wo_id_fk + "]");
                        return false;
                    }
                    //入账
                    btnFunc.move_in_func();
                }
            }else{
            	return false;
            }
        },
        addSelectOpe:function($selectDom,arr,valProp,txtProp1,txtProp2,firstSpace){
            var i,options;
            if(!arr){
                return false;
            }
            if(!$.isArray(arr)){
                arr = [arr];
            }
            $selectDom.empty();
            if(firstSpace === true){
                $selectDom.append("<option ></option>");
            }
            txtProp1 = (typeof(txtProp1)==="undefined" ? valProp :txtProp1);
            txtProp2 = (typeof(txtProp2)==="undefined" ? valProp :txtProp2);
            /***
             * 提高执行效率，避免多次给Select添加元素
             * 使用array.join("") 代替"+"拼接字符串
             */
            options = [];
            for(i=0;i<arr.length;i++){
                if(arr[i].toolg_id=='$FMA'||arr[i].toolg_id=='$FQC'||arr[i].toolg_id=='$MPK'){
                    continue;
                };
                options[i] = "<option value ="+ arr[i][valProp] +">" + arr[i][txtProp1]+":"+ arr[i][txtProp2]+ "</option>";
            }
            $selectDom.append(options.join(""));
            $selectDom.select2({
                theme : "bootstrap"
            });
        },
    };
    
    /**
     * All button click function
     * @type {Object}
     */
    var btnFunc = {
    	move_in_func : function(){
        	var prd_seq_id = $.trim(domObj.$prdSeqIdTxt.val());
        	if(!prd_seq_id){
                showErrorDialog("", "请输入屏体代码");
                return false;
        	}

            var tool_id = $.trim(domObj.$toolIdSel.val());
            if(!tool_id){
                showErrorDialog("", "请选择设备代码");
                return false;
            }

            //检查工单是否绑定线别，站点
            var woId = domObj.$woIdSel.val();
            var lineId = domObj.$bayIdSel.val();
            var opeId = domObj.$opeIdSel.val();

            var inObj1 = {
                trx_id     : VAL.T_MSPLINEWO,
                evt_usr    : VAL.EVT_USER,
                action_flg : "Q",
                line_id : lineId,
                wo_id : woId,
                ope_id: opeId,
                valid_flg : 'Y'
            };
            var outObj1 = comTrxSubSendPostJson(inObj1);
            if (outObj1.rtn_code == VAL.NORMAL) {
                if(outObj1.oary != null && outObj1.oary.length  > 0){
                    var inObj = {
                        trx_id     : VAL.T_FPPMOVEIN,
                        evt_usr    : VAL.EVT_USER,
                        action_flg : "A",
                        opi_ope_flg: "Y",
                        iary       : [{
                            prd_seq_id : prd_seq_id,
                            tool_id_fk : tool_id
                        }]
                    };
                    var outObj = comTrxSubSendPostJson(inObj);
                    if (outObj.rtn_code == VAL.NORMAL) {
                        domObj.grids.$prodListGrd.jqGrid("clearGridData");
                        showMessengerSuccessDialog("入账成功！",1);
                        domObj.$prdSeqIdTxt.val("");
                        domObj.$prdSeqIdTxt.focus();
                    }
                }else{
                    showErrorDialog("","工单"+woId+"未否绑定线别，站点!或未激活！重新选择！");
                }
            }
    	}
    };
    
    /**
     * Bind button click action
     */
    var iniButtonAction = function(){
        domObj.buttons.$move_in_btn.click(function(){
        	toolFunc.queryPrdInfo();
        });
    };
    
    /**
     * Ini contorl's data
     */
    var iniContorlData = function(){
    	$("input").val("");
    	toolFunc.initBayArea();
        toolFunc.iniOpeIdSel();
        toolFunc.iniToolIdSel();
        toolFunc.initWoCate();
        toolFunc.iniWoIdSel();
    };
    
    var otherActionBind = function(){
        //Stop from auto commit
        $("form").submit(function(){
            return false;
        });

        $(window).resize(function() {
        	toolFunc.resizeFnc();
        });
        
        domObj.$bayIdSel.change(function(){
        	toolFunc.iniToolIdSel();
        });
        
        domObj.$opeIdSel.change(function(){
        	toolFunc.iniToolIdSel();
        });
        
        domObj.$woCateSel.change(function(){
        	toolFunc.iniWoIdSel();
        });

        domObj.$prdSeqIdTxt.keydown(function(event){
            if(event.keyCode==13){
            	toolFunc.queryPrdInfo();
            }
        });
    };
    
    /**
     * Ini view, data and action bind
     */
    var initializationFunc = function(){
    	iniGridInfo();
    	toolFunc.resizeFnc();
        iniContorlData();
        iniButtonAction();
        otherActionBind();
    };
    
    initializationFunc();
});
